/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.power.service.impl;

import com.alipay.api.internal.util.codec.Base64;
import me.zhengjie.modules.power.domain.Power;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.power.repository.PowerRepository;
import me.zhengjie.modules.power.service.PowerService;
import me.zhengjie.modules.power.service.dto.PowerDto;
import me.zhengjie.modules.power.service.dto.PowerQueryCriteria;
import me.zhengjie.modules.power.service.mapstruct.PowerMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2022-04-08
**/
@Service
@RequiredArgsConstructor
public class PowerServiceImpl implements PowerService {

    private final PowerRepository powerRepository;
    private final PowerMapper powerMapper;

    @Override
    public Map<String,Object> queryAll(PowerQueryCriteria criteria, Pageable pageable){
        Page<Power> page = powerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(powerMapper::toDto));
    }

    @Override
    public List<PowerDto> queryAll(PowerQueryCriteria criteria){
        return powerMapper.toDto(powerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PowerDto findById(String id) {
        Power power = powerRepository.findById(id).orElseGet(Power::new);
        ValidationUtil.isNull(power.getId(),"Power","id",id);
        return powerMapper.toDto(power);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PowerDto create(Power resources) {
        resources.setId(IdUtil.simpleUUID()); 
        return powerMapper.toDto(powerRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Power resources) {
        Power power = powerRepository.findById(resources.getId()).orElseGet(Power::new);
        ValidationUtil.isNull( power.getId(),"Power","id",resources.getId());
        power.copy(resources);
        powerRepository.save(power);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            powerRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<PowerDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PowerDto power : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", power.getName());
            map.put("类型", power.getType());
            map.put("时间", power.getDatetime());
            map.put("电量", power.getPower());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    public String getBase64(String text) throws IOException {
        int imageWidth = 256;

        int imageHeight = 160;

        int fontSize = 16;

        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);

        //可以理解为画笔，为我们提供了各种绘制图形
        Graphics graphics = image.getGraphics();

        Font font = new Font("楷体", Font.PLAIN, fontSize);

        graphics.setFont(font);

        graphics.setColor(new Color(246, 96, 0));

        //画矩形边框
        graphics.fillRect(0, 0, imageWidth, imageHeight);

        graphics.setColor(new Color(255, 255, 255));

        int line=1;

        StringBuilder sb = new StringBuilder();
        sb.append(text);
        while(sb.length()>0) {
            int length = 0;
            int stopIndex = 0;
            /*循环内容的每个字符，判断该字符为英文还是中文*/
            for (int j = 0; j < sb.length(); j++){
                if (sb.charAt(j) < 129) {
                    length += fontSize * 0.5;
                } else {
                    length += fontSize;
                }
                if (length > imageWidth) {
                    break;
                }
                stopIndex = j;
            }

            graphics.drawString(sb.substring(0, stopIndex + 1), 0, line * fontSize);

            sb.delete(0, stopIndex + 1);
            line++;

        }

        File file = new File("D:\\abc.png");
        ImageIO.write(image, "PNG", file);
        // 将图片文件转化为二进制流
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 图片头

        String imghead = "data:image/jpeg;base64,";
        return imghead+ Base64.encodeBase64String(data);

    }
}